package com.graduate.after.web.control;

import com.alipay.api.AlipayApiException;
import com.graduate.after.bean.AliReturnPayBean;
import com.graduate.after.bean.ShopCarSingleInfo;
import com.graduate.after.config.PayConfig;
import com.graduate.after.config.WebSocket;
import com.graduate.after.constants.StatusCode;
import com.graduate.after.exception.GraduateException;
import com.graduate.after.service.ShopCarInfoService;
import com.graduate.after.utils.QRCodeUtils;
import com.graduate.after.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/shopCar")
public class ShopCarControl {

    private static Logger log = Logger.getLogger(ShopCarControl.class.getClass());

    @Autowired
    private ShopCarInfoService shopCarInfoService;

    @Autowired
    private WebSocket webSocket;

    @RequestMapping("/addCar")
    public Result addCar(String userName, Long shopIid){
        if(StringUtils.isBlank(userName) || shopIid == null) {
            throw new GraduateException(StatusCode.PARAM_IS_BLANK);
        }

        String info = shopCarInfoService.shopCarInfoInsert(userName, shopIid);
        if(Objects.equals(info,"One")) {
            return Result.success("购物车商品数量加一");
        }else if(Objects.equals(info,"Two")) {
            return Result.success("已添加进购物车");
        }else {
            return Result.fail(StatusCode.SYSTEM_INNER_ERROR);
        }

    }

    @RequestMapping("/selectCar")
    public Result selectAllCar(String userName){
        if(StringUtils.isBlank(userName)) {
            throw new GraduateException(StatusCode.PARAM_IS_BLANK);
        }
        System.out.println(userName);
        List<ShopCarSingleInfo> shopCarSingleInfos = shopCarInfoService.shopCarAllSelect(userName);
        Iterator<ShopCarSingleInfo> iterator = shopCarSingleInfos.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        return Result.success(shopCarSingleInfos);
    }

    @RequestMapping("/addOrder")
    public Result addOrder(String list) {
        if(StringUtils.isBlank(list)) {
            throw new GraduateException(StatusCode.PARAM_IS_BLANK);
        }
        String qrCode = null;
        Map map = null;
        try {
            map = shopCarInfoService.orderInfoInsert(list);
        } catch (AlipayApiException e) {
            return Result.fail(StatusCode.QRCODE_CREATE_IS_FAIL);
        }
        if(map == null) {
            return Result.fail(StatusCode.QRCODE_CREATE_IS_FAIL);
        }
        return Result.success(map);
    }

    @RequestMapping("/updateOrder")
    public Result updateOrder(String id) {
        if(id == null) {
            throw new GraduateException(StatusCode.PARAM_IS_BLANK);
        }
        shopCarInfoService.changeStatus(Long.parseLong(id));
        return Result.success();
    }

    /**
     * 支付宝回调函数
     * @param request
     * @param response
     * @param returnPay
     * @throws IOException
     */
    @RequestMapping("/call")
    public void call(HttpServletRequest request, HttpServletResponse response, AliReturnPayBean returnPay) throws IOException {
        response.setContentType("type=text/html;charset=UTF-8");
        log.info("支付宝的的回调函数被调用");
        if (!PayConfig.checkSign(request)) {
            log.info("验签失败");
            response.getWriter().write("failture");
            return;
        }
        if (returnPay == null) {
            log.info("支付宝的returnPay返回为空");
            response.getWriter().write("success");
            return;
        }
        log.info("支付宝的returnPay" + returnPay.toString());
        //表示支付成功状态下的操作
        if (returnPay.getTrade_status().equals("TRADE_SUCCESS")) {
            log.info("支付宝的支付状态为TRADE_SUCCESS");
            //业务逻辑处理 ,webSocket在下面会有介绍配置
            webSocket.sendMessage("true");
        }
        response.getWriter().write("success");
    }

    @RequestMapping("/selectOrder")
    public Result selectAllOrder(String userName,String type){
        if(StringUtils.isBlank(type)) {
            throw new GraduateException(StatusCode.PARAM_IS_BLANK);
        }
        List orderInfos = shopCarInfoService.OrderAllSelect(userName,type);
        System.out.println(orderInfos);
        return Result.success(orderInfos);
    }

    @RequestMapping("/refund")
    public Result refundOrderLine(String orderId, String orderLineId) {
        System.out.println(orderId);
        System.out.println(orderLineId);
        Long newOrderId = shopCarInfoService.refundOrderLine(Long.parseLong(orderId), Long.parseLong(orderLineId));
        if(newOrderId != null) {
            System.out.println(newOrderId);
            return Result.success(newOrderId);
        }else{
            return Result.success();
        }
    }

    @RequestMapping("/userAndOrderLineQRCode")
    public Result getQRCode(String codeContent, HttpServletResponse response) {
        try {
            String qrCode2Stream = QRCodeUtils.createQRCode2Stream(codeContent, response);

            // 将图片存储在本地文件里
//            String filePath = "/code.png";
//            System.out.println(filePath);
//            QRCodeUtils.createQRCode2File(codeContent,filePath);
//            BufferedImage bImage = ImageIO.read(new File(filePath));
//            ByteArrayOutputStream bos = new ByteArrayOutputStream();
//            ImageIO.write(bImage,"png",bos);
//            byte[] data1 = bos.toByteArray();
//            BASE64Encoder encoder = new BASE64Encoder();
//            String value = encoder.encode(data1);
//            System.out.println(value);
    


            log.info("成功生成二维码！");
            return Result.success(qrCode2Stream);
        } catch (Exception e) {
            log.error("发生错误， 错误信息是：{"+e.getMessage()+"}！");
            return Result.fail(StatusCode.SYSTEM_INNER_ERROR);
        }
    }
}
